import { resolve } from 'node:path';
import process from 'node:process';
import { ConfigEnv, defineConfig, loadEnv } from 'vite'
import uni from '@dcloudio/vite-plugin-uni'
import tailwindcss from 'tailwindcss'
import autoprefixer from 'autoprefixer'
import postcssRemToResponsivePixel from 'postcss-rem-to-responsive-pixel'
import postcssWeappTailwindcssRename from 'weapp-tailwindcss-webpack-plugin/postcss'
import vwt from 'weapp-tailwindcss-webpack-plugin/vite'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'

const isH5 = process.env.UNI_PLATFORM === 'h5'
const isApp = process.env.UNI_PLATFORM === 'app'
const weappTailwindcssDisabled = isH5 || isApp

const postcssPlugin = [autoprefixer(), tailwindcss()]
if (!weappTailwindcssDisabled) {
    postcssPlugin.push(
        postcssRemToResponsivePixel({
            rootValue: 32,
            propList: ['*'],
            transformUnit: 'rpx'
        })
    )
    postcssPlugin.push(postcssWeappTailwindcssRename())
}

const viteConfig = defineConfig((mode: ConfigEnv) => {
    const env = loadEnv(mode.mode, process.cwd())
    return {
        plugins: [
            uni(), 
            AutoImport({
                imports: ['vue', 'vue-router', 'pinia', 'uni-app'], // 自动导入的依赖库数组
                dts: './auto-imports.d.ts', // 自动导入类型定义文件路径
            }),
            Components({
                resolvers: [],
            }),
            weappTailwindcssDisabled ? undefined : vwt()
        ],
        css: {
            postcss: {
                plugins: postcssPlugin
            }
        },
        // server: {
        //     port: 8088,
        //     hmr: true, // 启用热更新
        //     proxy: {
        //         '/api': {
        //             target: env.VITE_APP_BASE_URL, // 目标服务器地址
        //             changeOrigin: true, // 是否修改请求头中的 Origin 字段
        //             rewrite: (path) => path.replace(/^\/api/, '')
        //         },
        //         '/mobile/api': {
        //             target: env.VITE_APP_BASE_URL, // 目标服务器地址
        //             changeOrigin: true, // 是否修改请求头中的 Origin 字段
        //             rewrite: (path) => path.replace(/^\/mobile\/api/, '')
        //         }
        //     }
        // }
    }
})

// https://vitejs.dev/config/
export default viteConfig
